require('express-async-errors');
const path = require('path');
const express = require('express');
const app = express();
const connectDB = require('./db/connectDB');
const errCaptureMiddleware = require('./middleware/err-capture');
const notFoundMiddleware = require('./middleware/not-found');

require('dotenv').config();
const PORT = process.env.PORT;


app.use(express.static(path.resolve(__dirname, 'public')));
app.use(express.json());

const cookieParser = require('cookie-parser');
app.use(cookieParser(process.env.COOKIE_SECRET, { signedCookies: true }));

// 安全策略
const mouteSecurity = require('./utils/mouteSecurity');
mouteSecurity(app);

// 注册路由
const mountRoutes = require('./routes/index');
mountRoutes(app);

app.get('/doc', (req, res) => {
   res.sendFile(
      path.resolve(__dirname, 'public', 'doc.html')
   );
});  
app.get('*', (req, res) => {
   res.sendFile(
      path.resolve(__dirname, 'public', 'index.html')
   );
});  

app.use(notFoundMiddleware)
app.use(errCaptureMiddleware); // 全局错误捕获

const start = async () => {
   try {
      await connectDB(process.env.MONGO_URI);
      app.listen(PORT, console.log(`Server is running on port ${PORT}`));
   } catch (error) {
      console.log(error);
   }
};

start();
